package org.icnmasjid.member.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.Activity;
import org.icnmasjid.member.service.Manager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class ActivityFormController extends BaseFormController {
    public ActivityFormController() {
        setCommandName("activity");
        setCommandClass(Activity.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        Activity activity = null;

        if (!StringUtils.isEmpty(id)) {
            activity = (Activity) manager.getObject(Activity.class, new Integer(id));
        } else {
            activity = new Activity();
        }

        return activity;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        Activity activity = (Activity) command;
        boolean isNew = (activity.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            manager.removeObject(Activity.class, activity.getId());

            saveMessage(request, getText("activity.deleted", locale));
        } else {
            manager.saveObject(activity);

            String key = (isNew) ? "activity.added" : "activity.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editActivity.html", "id", activity.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
